﻿/**
* @file qochatwidget.cpp
* @describe 聊天对话框
* @author gaoyuelong
* @date 2021/11/23
*/

#include "qochatwidget.h"
#include "qochatlist.h"
#include "ui_qochatwidget.h"
#include "qousercontrol.h"
#include <QKeyEvent>
#include <QAbstractSlider>
#include <QScrollBar>
#include <QDateTime>

#define BLUE 0,0,255
#define BLACK 0,0,0

QoChatWidget::QoChatWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QoChatWidget)
{
    ui->setupUi(this);
    setFocus();
    ui->texteditInput->installEventFilter(this);
    connect(QoUserControl::getInstance(), SIGNAL(signalRecvMsg(const QString &)),
            this, SLOT(slotUpdateMsg(const QString &)));
    connect(ui->texteditChatMsg->verticalScrollBar(), &QAbstractSlider::rangeChanged, this, &QoChatWidget::slider);
}

QoChatWidget::~QoChatWidget()
{
    delete ui;
}

bool QoChatWidget::eventFilter(QObject *pObj, QEvent *pEvent)
{
    if (pObj == ui->texteditInput) {
        QKeyEvent *pKeyEvent = dynamic_cast<QKeyEvent *>(pEvent);
        if (pKeyEvent) {
            if (pKeyEvent->key() == Qt::Key_Return || pKeyEvent->key() == Qt::Key_Return) {
                QTextCursor tmpCursor = ui->texteditInput->textCursor();
                tmpCursor.setPosition(0);
                ui->texteditInput->setTextCursor(tmpCursor);
                on_btnSend_clicked();
            }
        }
    }
    return QWidget::eventFilter(pObj, pEvent);
}

void QoChatWidget::setToAccount(const QString &strToAccount)
{
    this->strToAccount = strToAccount;
    setWindowTitle("To:" + strToAccount);
}

//点击发送消息
void QoChatWidget::on_btnSend_clicked()
{
    //检查要发送的是否为空
    if (ui->texteditInput->toPlainText().isEmpty()) {
        return;
    }

    QString strSend = ui->texteditInput->toPlainText();

    //去除回车
    strSend.remove(QChar('\n'));
    //判断输入框是否为空
    if (strSend.isEmpty()) {
        return ;
    }

    QoUserControl::getInstance()->chat(strToAccount, strSend);

    formatMsg(E_WHOSAY::eMe, strSend);

    ui->texteditChatMsg->append(strSend);

    //清空输入框
    ui->texteditInput->clear();
}

void QoChatWidget::slotUpdateMsg(const QString &strMsg)
{
    //格式化文字
    QString strTmpMsg = strMsg;
    formatMsg(E_WHOSAY::eFriend, strTmpMsg);
    ui->texteditChatMsg->append(strTmpMsg);
}

void QoChatWidget::slider()
{
    ui->texteditChatMsg->verticalScrollBar()->setValue(ui->texteditChatMsg->verticalScrollBar()->maximum());
}

void QoChatWidget::formatMsg(E_WHOSAY eWhoSay, QString &strMsg)
{
    if (eWhoSay == E_WHOSAY::eMe) {
        ui->texteditChatMsg->setTextColor(QColor(BLACK));
    } else if (eWhoSay == E_WHOSAY::eFriend) {
        ui->texteditChatMsg->setTextColor(QColor(BLUE));
    }

    strMsg = QDateTime::currentDateTime().toString("[yyyy.dd.MM hh:mm:ss]: %1").arg(strMsg);
}

//加载历史消息
void QoChatWidget::loadHistoryMsg()
{

}
